#!/usr/bin/env python3

# -*- coding: utf-8 -*-
# File Name: MistuneExtension.py
# Author: bobo
# Created Time: 20241206

from utils import log

logger = log.get_logger()

BLOCK_HEDGE_ALERT = (
    r"^:{3}(?P<alert_type>.+?)\n"  # 头以:::开始
    r"(?P<alert_text>[\s\S]+?)"  # 信息 \s\S表示任意字符
    r"\n:{3}"  # 结尾:::
)


def parse_block_hedge_alert(block, m, state):
    """
    样例
    ::: primary|secondary|success|danger|warning|info
    :::
    """
    ttype = m.group("alert_type")
    text = m.group("alert_text")
    logger.debug(f"TYPE:{ttype}")
    logger.debug(f"TEXT:{text}")
    children = [{"type": "paragraph", "text": text}]
    state.append_token(
        # {"type": "block_hedge_alert", "raw": txt, "attrs": {"alert_type": t}}
        {
            "type": "block_hedge_alert",
            "children": children,
            "attrs": {"ttype": ttype},
        }
    )
    return m.end() + 1


def render_block_hedge_alert(renderer, text, ttype):
    logger.debug(f"Attrs:{ttype}")
    t = ttype.split()
    title = "TIP"
    if len(t) > 1:
        title = t[1]
    template = f'<div class="alert alert-{t[0]}" role="alert">\n <p><strong> <span> {title} </span></strong></p>\n {text} \n </div>\n'
    return template


def hedgeAlert(md):
    md.block.register("block_hedge_alert", BLOCK_HEDGE_ALERT, parse_block_hedge_alert)
    if md.renderer and md.renderer.NAME == "html":
        md.renderer.register("block_hedge_alert", render_block_hedge_alert)
